import React from 'react';
import {connect} from 'dva/index';
import {Button, Col, DatePicker, Form, Input, Radio, Row, Select, Table} from 'antd';
import Constants from '../../utils/Constants';
import RightConstants from '../../utils/RightConstants';
import RightBox from '../../components/common/rightBox';
import PortSelect from '../../components/common/portSelect';
import RoleSelect from '../../components/common/roleSelect';
import DeliveryReceiptDetail from '../../components/logisticsOrder/deliveryReceiptDetail';

const FormItem = Form.Item;
const R = require("ramda");
const RadioGroup = Radio.Group;
const { RangePicker } = DatePicker;

const orderBusiness = Form.create()(class OrderBusiness extends React.Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        this.props.dispatch({ type: 'deliveryReceipt/getListForPage', payload: { page: Constants.DEFAULT_PAGE } });
        this.props.dispatch({ type: 'berthingCompany/getAllBerthingCompanys' }); //查询船公司
    }

    handleOpen = (id, disabled, accept, cstEdit, marketUpdate) => {
        this.props.dispatch({
            type: 'deliveryReceipt/getById',
            payload: { id }
        })
        this.props.dispatch({ type: 'supplier/getSupplierList', payload: { supplierType: Constants.SUPPLIER_TYPE.FRAE } });  //查询海运供应商
        this.props.dispatch({ type: 'supplier/getDecSupplierList' });  //查询报关供应商List
        this.props.dispatch({ type: 'supplier/getTraSupplierList' });  //查询拖车供应商List
        this.props.dispatch({ type: 'supplier/getAirSupplierList' });  //查询空运供应商List
        this.props.dispatch({ type: 'supplier/getExpSupplierList' });  //查询快递供应商List
        this.props.dispatch({ type: 'supplier/getInsSupplierList' });  //查询保险供应商List
        this.props.dispatch({ type: 'supplier/getStoSupplierList' });  //查询仓内装供应商List
        this.props.dispatch({ type: 'supplier/getInspectionSupplierList' });  //查询商检供应商List
        this.props.dispatch({ type: 'supplier/getCoSupplierList' });  //查询产地证供应商List

        this.props.dispatch({ type: 'airCompany/getAllAirCompanys' }); //查询航空公司
        this.deliveryReceiptDetail.handleOpen(disabled, accept, null, cstEdit, null, false, null, false, marketUpdate, false );
    }

    handleSearch = flag => {
        let values = this.props.form.getFieldsValue();
        values.drBeginTime = R.isNil(values.deliveryTime) || R.isEmpty(values.deliveryTime) ? null : values.deliveryTime[0].format(Constants.DATEFORMAT);
        values.drEndTime = R.isNil(values.deliveryTime) || R.isEmpty(values.deliveryTime) ? null : values.deliveryTime[1].format(Constants.DATEFORMAT);
        values.bkBeginTime = R.isNil(values.bookingTime) || R.isEmpty(values.bookingTime) ? null : values.bookingTime[0].format(Constants.DATEFORMAT);
        values.bkEndTime = R.isNil(values.bookingTime) || R.isEmpty(values.bookingTime) ? null : values.bookingTime[1].format(Constants.DATEFORMAT);
        values.deliveryTime = undefined;
        values.bookingTime = undefined;
        let newPage = this.props.deliveryReceipt.page;
        if (flag) newPage.page = 1;
        this.props.dispatch({
            type: 'deliveryReceipt/getListForPage',
            payload: {
                ...values,
                page: newPage
            }
        });
    };

    columns = [
        { title: '服务类型', key: 'serviceItems',
            render: record =>{
                return <span>{record.shipping ? "海运" : null}
                             {record.airFreight ? "空运" : null}
                             {record.portService ? (record.shipping || record.airFreight ? "/港前" : "港前") : null}
                             {record.vasService ? (record.shipping || record.airFreight || record.portService ? "/增值" : "增值") : null}
                        </span>
            }
        },
        { title: '交接单号', dataIndex: 'receiptNo', key: 'receiptNo' },
        { title: '订单号', dataIndex: 'orderno', key: 'orderno' },
        { title: '客户名称', dataIndex: 'companyName', key: 'companyName' },
        {   title: 'SO', 
            render: record=>{
                return <span>{record.soNo ? record.soNo : '—' }</span>
            } 
        },
        {
            title: '起运港',
            render: record => {
                return <span>
                    <div>{record.loadingPortNameEn}</div>
                    <div>({record.loadingPortName})</div>
                </span>
            }
        },
        {
            title: '目的港',
            render: record => {
                return <span>
                    <div>{record.destinationPortNameEn}</div>
                    <div>({record.destinationPortName})</div>
                </span>
            }
        },
        { title: '业务员', dataIndex: 'creatorName', key: 'creatorName' },
        { title: '操作员', dataIndex: 'gdUserName', key: 'gdUserName' },
        { title: '接单时间', 
            render: record =>{
                return <span>{record.orderCreattime ? record.orderCreattime : "未接单"}</span>
            }
        },
        {
            title: '状态', render(record) {
                if (record.drStatus == '2') {
                    return '待接单';
                } else if (record.drStatus == '3') {
                    return '已转订单';
                } else if (record.drStatus == '4') {
                    return '已退回';
                } else if(record.drStatus == '5'){
                    return '订舱中已转订单';
                }
            }
        },
        {
            title: '操作',
            render: (record) => {
                let acceptLink = <RightBox resource={RightConstants.DELIVERYRECEIPT.DELIVERYRECEIPT_ACCEPT}><a href="#" onClick={this.handleOpen.bind(this, record.id, true, true, true, false)}>接单</a></RightBox>
                let viewLink = <a href="#" onClick={this.handleOpen.bind(this, record.id, true, true, true, false)}>查看</a>
                let marketUpdate = <RightBox resource={RightConstants.DELIVERYRECEIPT.DELIVERYRECEIPT_MARKET_UPDATE} split={true}><a href="#" onClick={this.handleOpen.bind(this, record.id, true, true, true, true)}>市场修改</a></RightBox>
                marketUpdate = record.drStatus === '3' || record.drStatus === '5' ? marketUpdate : null;
                return <span>{record.drStatus == "2" ? acceptLink : null}{marketUpdate}{["3", "4", "5"].includes(record.drStatus) ? viewLink : null}</span>
            }
        }
    ];

    render() {
        let formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 16 } };
        const { getFieldDecorator } = this.props.form;
        let berthingCompanyList = this.props.berthingCompany.berthingCompanyList ? this.props.berthingCompany.berthingCompanyList : [];
        let values = this.props.form.getFieldsValue();
        values.drBeginTime = R.isNil(values.deliveryTime) || R.isEmpty(values.deliveryTime) ? null : values.deliveryTime[0].format(Constants.DATEFORMAT);
        values.drEndTime = R.isNil(values.deliveryTime) || R.isEmpty(values.deliveryTime) ? null : values.deliveryTime[1].format(Constants.DATEFORMAT);
        values.bkBeginTime = R.isNil(values.bookingTime) || R.isEmpty(values.bookingTime) ? null : values.bookingTime[0].format(Constants.DATEFORMAT);
        values.bkEndTime = R.isNil(values.bookingTime) || R.isEmpty(values.bookingTime) ? null : values.bookingTime[1].format(Constants.DATEFORMAT);
        values.deliveryTime = undefined;
        values.bookingTime = undefined;
        let pagination = {
            showTotal: total => `共 ${total} 条数据`,
            pageSize: this.props.deliveryReceipt.page.size,
            current: this.props.deliveryReceipt.page.page,
            total: this.props.deliveryReceipt.page.totalRow,
            showSizeChanger: true,
            onShowSizeChange: (current, size) => {
                let newPage = this.props.deliveryReceipt.page;
                newPage.size = size;
                newPage.page = 1;
                this.props.dispatch({
                    type: 'deliveryReceipt/getListForPage',
                    payload: {
                        ...values,
                        page: newPage
                    }
                });
            },
            onChange: (pageNumber, pageSize) => {
                let newPage = this.props.deliveryReceipt.page;
                newPage.page = pageNumber;
                this.props.dispatch({
                    type: 'deliveryReceipt/getListForPage',
                    payload: {
                        ...values,
                        page: newPage
                    }
                });
            }
        }

        return (
            <div>
                <Row>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'客户名称'}>
                            {getFieldDecorator('cstName')
                                (
                                <Input maxLength="20" />
                                )
                            }
                        </FormItem>
                    </Col>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'船公司'}>
                            {getFieldDecorator('berthingName')(
                                <Select style={{ width: '100%' }} showSearch placeholder="可根据关键字搜索" allowClear
                                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
                                    {
                                        !R.isNil(berthingCompanyList) ? berthingCompanyList.map(item => {
                                            return (<Select.Option value={item.id + ""} key={item.id + ""}>{item.berthingCode}</Select.Option>);
                                        }) : ''
                                    }
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                </Row>

                <Row>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'交接单号/订单号'}>
                            {getFieldDecorator('orderNo')
                                (
                                <Input maxLength="20" placeholder="可根据交接单号或订单号搜索" style={{ width: '100%' }} />
                                )
                            }
                        </FormItem>
                    </Col>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'SO号'}>
                            {getFieldDecorator('soNo')
                                (
                                <Input maxLength="20" placeholder="可根据SO号搜索" style={{ width: '100%' }} />
                                )
                            }
                        </FormItem>
                    </Col>
                </Row>

                <Row>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'业务员'}>
                            {getFieldDecorator('ywUser')
                            (
                            <RoleSelect role={Constants.ROLE.SALES_MAN} style={{ width: '100%' }} />
                            )}
                        </FormItem>
                    </Col>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'操作员'}>
                            {getFieldDecorator('gdUser')(
                                <RoleSelect role={Constants.ROLE.GD_MAN} style={{ width: '100%' }} />   
                            )}
                        </FormItem>
                    </Col>
                </Row>

                <Row>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'起运港'}>
                            {getFieldDecorator('loadingPort')(
                                <PortSelect style={{ width: '100%' }} allowClear />
                            )}
                        </FormItem>

                    </Col>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'目的港'}>
                            {getFieldDecorator('destinationPort')(
                                <PortSelect style={{ width: '100%' }} allowClear />
                            )}
                        </FormItem>
                    </Col>
                </Row>

                <Row>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'下单时间'}>
                            {getFieldDecorator('deliveryTime')(
                                <RangePicker
                                    style={{ width: '100%' }}
                                    showTime={{ format: 'YYYY-MM-DD' }}
                                    format="YYYY-MM-DD"
                                    placeholder={['开始时间', '结束时间']}
                                />
                            )}
                        </FormItem>
                    </Col>
                    {/* <Col span={6}>
                        <FormItem {...formItemLayout} label={'放仓时间'}>
                            {getFieldDecorator('bookingTime')
                                (
                                <RangePicker
                                    style={{ width: 237 }}
                                    showTime={{ format: 'YYYY-MM-DD' }}
                                    format="YYYY-MM-DD"
                                    placeholder={['开始时间', '结束时间']}
                                />
                                )}
                        </FormItem>
                    </Col> */}
                </Row>
                <Row>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'状态'}>
                            {getFieldDecorator('drStatus', {
                                initialValue: ""
                            })(
                                <RadioGroup style={{width: 800}} >
                                    <Radio value="">全部</Radio>
                                    <Radio value="2">待接单</Radio>
                                    <Radio value="5">订舱中已转订单</Radio>
                                    <Radio value="3">已转订单</Radio>
                                    <Radio value="4">已退回</Radio>
                                </RadioGroup>
                        )}
                        </FormItem>
                    </Col>
                    <Col span={7} style={{ float: 'right' }}>
                        <Button type="primary" icon="search" style={{ marginRight: 5 }} onClick={this.handleSearch.bind(this, true)} size={'default'}>查询</Button>
                    </Col>
                </Row>


                <Table loading={this.props.loading} rowKey='id' dataSource={this.props.deliveryReceipt.list} columns={this.columns} bordered={true} size={'middle'} pagination={pagination}
                    title={() => <span style={{ color: 'red' }}>市场接单记录</span>} />
                <DeliveryReceiptDetail wrappedComponentRef={(inst) => this.deliveryReceiptDetail = inst} refreshList={this.handleSearch} />
            </div >
        );
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.deliveryReceipt, deliveryReceipt: state.deliveryReceipt, berthingCompany: state.berthingCompany
    };
}

export default connect(mapStateToProps)(orderBusiness);
